package palindrome;

import java.util.ArrayList;
import java.util.List;

public class Palindrome {

    private String value;
    private char[] charArrayValue;
    private int unpairedLengthStep = 1;
    private int pairedLengthStep = 1;

    public Palindrome(String value) {
        this.value = value;
        charArrayValue = value.toCharArray();
    }

    public List<String> getPalindroms() {
        List<String> result = new ArrayList<String>();
        result.addAll(getUnpairedPalindromeList());
        result.addAll(getPairedPalindromeList());        
        return result;
    }

    private List<String> getUnpairedPalindromeList() {
        List<String> result = new ArrayList<String>();
        for (int i = 1; i < charArrayValue.length - 1; i++) {
            if (charArrayValue[i - 1]
                    == charArrayValue[i + 1]) {
                result.add(value.substring(i - 1,
                        i + 1 + 1));
                result.addAll(getElsePalindromeList(i, unpairedLengthStep,
                        unpairedLengthStep));
            }
        }
        return result;
    }

    private List<String> getPairedPalindromeList() {
        List<String> result = new ArrayList<String>();
        for (int i = 0; i < (charArrayValue.length - 1); i++) {
            if (charArrayValue[i] == charArrayValue[i + 1]) {
                result.addAll(getElsePalindromeList(i, pairedLengthStep, 
                        pairedLengthStep -1));
            }
        }
        return result;
    }

    private List<String> getElsePalindromeList(int rootNumber, 
            int leftStep, int rightStep) {
        List<String> result = new ArrayList<String>();
        while (leftStep <= (charArrayValue.length / 2)) {
            leftStep++;
            rightStep++;
            int resultListSize = result.size();
            if ((rootNumber >= rightStep)
                    && (rootNumber < (charArrayValue.length - leftStep))
                    && (charArrayValue[rootNumber - rightStep]
                    == charArrayValue[rootNumber + leftStep])) {
                result.add(value.substring(rootNumber - rightStep,
                        rootNumber + leftStep + 1));
            }
            if (result.size() == resultListSize) {
                break;
            }
        }
        return result;
    }
}
